<?php

namespace App\Service;

use Hyperf\HttpMessage\Upload\UploadedFile;

class FileService
{

    public function uploadFileOne(UploadedFile $uploadedFile)
    {
        if (!$uploadedFile->isValid()){
            return [false,'上传失败'];
        }
        $fileDriver = make(\Hyperf\Filesystem\FilesystemFactory::class)->get('local');
        $tempPath = $uploadedFile->getRealPath();
        $mdfFile = md5_file($tempPath);
        $contents = file_get_contents($tempPath);
        $savePath = '/upload/'.date('Y/m/d/').$mdfFile . '.' .$uploadedFile->getExtension();
        $fileDriver->write($savePath, $contents);
        if(!$fileDriver->fileExists($savePath)){
            return [false,'文件保存失败'];
        }
        return [true, [
            'path' => $savePath,
            'url'  => rtrim(\Hyperf\Config\config('file.storage.local.read_url'),'/'). $savePath,
            'org_file_name' => $uploadedFile->getClientFilename(),
        ]];
    }

    public function writeFile($contents, $fileName)
    {
        $savePath = '/upload/'.date('Y/m/d/').$fileName;
        $fileDriver = make(\Hyperf\Filesystem\FilesystemFactory::class)->get('local');
        $fileDriver->write($savePath, base64_decode($contents));
        if(!$fileDriver->fileExists($savePath)){
            return [false,'文件保存失败'];
        }
        return [true, [
            'path' => $savePath,
            'url'  => rtrim(\Hyperf\Config\config('file.storage.local.read_url'),'/'). $savePath,
            'org_file_name' =>$fileName,
        ]];
    }
}